<template>
	<view class="real-info">
		<view class="form-box">
			<u--form ref="uForm" :model="form" :rules="rules" labelPosition="left" labelWidth="180rpx">
				<u-form-item labelWidth="auto" prop="idcard">
					<view class="idcard-box">
						<view class="label-box">
							<text class="label">身份证照片</text>
							<text class="tips">（请确保身份证边框完整，字体清晰，无反光）</text>
						</view>
						<view class="image-box">
							<u-upload
								:fileList="id_frontend"
								name="id_frontend"
								:maxCount="1"
								width="300rpx"
								height="260rpx"
								@afterRead="afterRead"
								@delete="deletePic"
							>
								<view class="box">
									<image class="image" src="@/static/idcrad-1.png" mode="aspectFill"></image>
									<view class="text">上传人像面</view>
								</view>
							</u-upload>
							<u-upload
								:fileList="id_backend"
								name="id_backend"
								:maxCount="1"
								width="300rpx"
								height="260rpx"
								@afterRead="afterRead"
								@delete="deletePic"
							>
								<view class="box">
									<image class="image" src="@/static/idcrad-2.png" mode="aspectFill"></image>
									<view class="text">上传国徽面</view>
								</view>
							</u-upload>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="真实姓名" prop="name">
					<u--input v-model="form.name" placeholder="请输入真实姓名" border="none"></u--input>
				</u-form-item>
				<u-form-item label="身份证号码" prop="idNumber">
					<u--input v-model="form.idNumber" placeholder="请输入身份证号码" border="none"></u--input>
				</u-form-item>
				<u-form-item label="性别" prop="sex">
					<u-radio-group v-model="form.sex" activeColor="#5749f7" placement="row">
						<u-radio :customStyle="{ marginRight: '8px'}" label="男" name="男"></u-radio>
						<u-radio label="女" name="女"></u-radio>
					</u-radio-group>
				</u-form-item>
				<picker mode="selector" :range="ethnicitys" @change="ethnicityChange">
					<u-form-item label="民族" prop="ethnicity">
						<u--input v-model="form.ethnicity" border="none" placeholder="请选择民族" disabled disabledColor="#fff"></u--input>
						<u-icon slot="right" name="arrow-right" color="#666" size="20rpx"></u-icon>
					</u-form-item>
				</picker>
				<picker mode="date" start="1920-01-01" @change="bindDateChange">
					<u-form-item label="生日" prop="birthDate">
						<u--input v-model="form.birthDate" border="none" placeholder="请选择生日" disabled disabledColor="#fff"></u--input>
						<u-icon slot="right" name="arrow-right" color="#666" size="20rpx"></u-icon>
					</u-form-item>
				</picker>
				<u-form-item label="住址" prop="address">
					<u--input v-model="form.address" border="none" placeholder="请输入"></u--input>
				</u-form-item>
				<u-form-item label="签发机关" prop="issueAuthority">
					<u--input v-model="form.issueAuthority" placeholder="请输入签发机关" border="none"></u--input>
				</u-form-item>
				<u-form-item label="有效期类型">
					<u-radio-group v-model="isLongTerm" activeColor="#5749f7" placement="row">
						<u-radio label="非长期有效" name="非长期有效" :customStyle="{marginRight: '24rpx'}"></u-radio>
						<u-radio label="长期有效" name="长期有效"></u-radio>
					</u-radio-group>
				</u-form-item>
				<block v-if="isLongTerm == '非长期有效'">
					<u-form-item label="有效期" prop="validPeriod" @click="showPop">
						<u--input v-model="form.validPeriod" border="none" placeholder="请选择有效期" disabled disabledColor="#fff"></u--input>
						<u-icon slot="right" name="arrow-right" color="#666" size="20rpx"></u-icon>
					</u-form-item>
				</block>
			</u--form>
		</view>
		
		<view class="bottom-box">
			<button class="btn" @click="submit">确认提交</button>
		</view>

		<lingfeng-timepicker ref="timePop" type="date-range" :maxDate="maxDate" @change="validPeriodChange"></lingfeng-timepicker>
	</view>
</template>

<script>
	import { uploadURL } from '@/api/config.js'
	import { setRealInfo, alyocr } from '@/api/api'

	export default {
		data () {
			return {
				isLongTerm: '非长期有效',
				id_frontend: [],
				id_backend: [],
				form: {
					name: '',
					sex: '',
					ethnicity: '',
					birthDate: '',
					address: '',
					idNumber: '',
					issueAuthority: '',
					validPeriod: '',
					id_frontend: '',
					id_backend: '',
				},
				rules: {
					idcard: {
						validator: () => {
							return !!(this.form.id_frontend && this.form.id_backend)
						},
						message: '请上传身份证照片', trigger: 'blur'
					},
					name: { required: true, message: '请输入真实姓名', trigger: 'blur' },
					sex: { required: true, message: '请选择性别', trigger: 'blur' },
					ethnicity: { required: true, message: '请选择民族', trigger: 'blur' },
					birthDate: { required: true, message: '请选择生日', trigger: 'blur' },
					address: { required: true, message: '请输入住址', trigger: 'blur' },
					idNumber: { required: true, message: '请输入身份证号码', trigger: 'blur' },
					issueAuthority: { required: true, message: '请输入签发机关', trigger: 'blur' },
					validPeriod: { required: true, message: '请选择有效期', trigger: 'blur' },
				},
				
				ethnicitys: ['汉族', '壮族', '满族', '回族', '苗族', '维吾尔族', '土家族', '彝族', '蒙古族', '藏族', '布依族', '侗族', '瑶族', '白族', '朝鲜族',
					'哈尼族', '哈萨克族', '黎族', '傣族', '畲族', '傈僳族', '佤族', '拉祜族', '景颇族', '高山族', '水族', '东乡族', '纳西族', '柯尔克孜族',
					'土族', '达斡尔族', '仫佬族', '羌族', '布朗族', '撒拉族', '毛南族', '仡佬族', '锡伯族', '阿昌族', '普米族', '塔吉克族', '怒族', '乌孜别克族',
					'俄罗斯族', '鄂温克族', '鄂伦春族', '德昂族', '保安族', '裕固族', '京族', '塔塔尔族', '独龙族', '赫哲族', '门巴族', '珞巴族', '基诺族'
				],
				maxDate: {
					year: 2125,
					month: 1,
					date: 1,
					hour: 23,
					minute: 59,
					second: 59
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			ethnicityChange(e) {
				const index = e.detail.value
				this.form.ethnicity = this.ethnicitys[index]
			},
			bindDateChange (e) {
				const arr = e.detail.value.split('-')
				this.form.birthDate = `${arr[0]}年${arr[1]}月${arr[2]}日`
			},
			regionChange (e) {
				this.form.address = e.detail.value.join('')
			},
			showPop () {
				this.$refs.timePop.show()
			},
			validPeriodChange (e) {
				this.form.validPeriod = `${e[0]}-${e[1]}`
			},
			
			// 删除图片
			deletePic(event) {
				this[event.name].splice(event.index, 1)
				
				this.form[event.name] = ''
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[event.name].length
				lists.map((item) => {
					this[event.name].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					this.uploadFilePromise(lists[i].url).then(result => {
						let item = this[event.name][fileListLen]
						this[event.name].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result.path
						}))
						this.form[event.name] = result.id
						fileListLen++
						
						this.alyocrImg(event.name, result.path)
					}).catch(() => {
						let item = this[event.name][fileListLen]
						this[event.name].splice(fileListLen, 1, Object.assign(item, {
							status: 'failed',
							message: '上传失败',
						}))
						fileListLen++
					})
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: uploadURL, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'img',
						success: (res) => {
							const data = JSON.parse(res.data)
							if (data.code == 1) {
								resolve({
									path: data.path,
									id: data.id
								})
							} else {
								reject()
							}
						}
					});
				})
			},
			
			alyocrImg (name, url) {
				uni.showLoading({ mask: true })
				alyocr({ url }).then(res => {
					uni.hideLoading({ noConflict: true })
					if (res) {
						console.log(res);
						const data = res.data
						
						if (name == 'id_backend') {
							this.form.issueAuthority = data.issueAuthority
							this.form.validPeriod = data.validPeriod
							if (data.validPeriod == '长期有效') {
								this.isLongTerm = '长期有效'
							}
						} else if (name == 'id_frontend') {
							this.form.name = data.name
							this.form.idNumber = data.idNumber
							this.form.sex = data.sex
							this.form.ethnicity = data.ethnicity
							this.form.birthDate = data.birthDate
							this.form.address = data.address
						}
					}
				})
			},
			
			submit () {
				if (this.isLongTerm == '长期有效') {
					this.form.validPeriod = '长期有效'
				}
				
				this.$refs.uForm.validate().then(valid => {
					if (valid) {
						uni.showLoading({ mask: true })
						setRealInfo(this.form).then(res => {
							uni.hideLoading({ noConflict: true })
							if (res) {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})

								setTimeout(() => {
									uni.navigateBack()
								}, 500)
							}
						})
					}
				}).catch(errors => {
					console.log('loginSubmit errors');
				})
			}
		}
	}
</script>

<style lang="scss">
.real-info {
	box-sizing: border-box;
	min-height: 100%;
	padding-bottom: 132rpx;
	padding-bottom: calc(132rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(132rpx + env(safe-area-inset-bottom));
	background-color: #f5f5f5;
	.form-box {
		padding: 0 32rpx;
		background-color: #fff;
	}
	.idcard-box {
		.label-box {
			.label {
				color: #303133;
				font-size: 15px;
			}
			.tips {
				color: #ff4c0d;
				font-size: 24rpx;
			}
		}
		.image-box {
			margin-top: 30rpx;
			display: flex;
			justify-content: space-between;
			.box {
				box-sizing: border-box;
				width: 300rpx;
				height: 260rpx;
				border: 1rpx solid #e5e5e5;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				.image {
					width: 244rpx;
					height: 154rpx;
				}
				.text {
					margin-top: 30rpx;
					color: #333;
					font-size: 28rpx;
				}
			}
		}
	}
	.bottom-box {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 10;
		height: 112rpx;
		padding: 0 20rpx;
		padding-bottom: 0;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		background-color: #fff;
		display: flex;
		align-items: center;
		.btn {
			flex: 1;
			margin: 0;
			border-radius: 72rpx;
			color: #fff;
			font-size: 28rpx;
			font-weight: bold;
			line-height: 72rpx;
			background-color: #5749f7;
		}
	}
}
</style>
